package com.robot.interceptors;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.robot.common.api.CurrentUserSupport;
import com.robot.dao.dto.IntegralDTO;
import com.robot.dao.feigndto.context.RequestContext;
import com.robot.dao.vo.IntegralVO;
import com.robot.dao.vo.UserInfoVO;
import com.robot.service.IntegralService;
import com.robot.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class IntegralAccountInterceptor implements HandlerInterceptor {


    @Autowired
    private CurrentUserSupport currentUserSupport;

    @Autowired
    private IntegralService integralService;

    @Autowired
    private UserService userService;


    @Override
    //todo 后面可以做个账户id、积分账户id缓存，避免冗余db操作给db的压力。
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("[IntegralAccountInterceptor.preHandle]start");
        Long userId = currentUserSupport.getCurrentUserId();

        // 把登录用户的ID和账号ID放到全局上下文ctx里。
        UserInfoVO userInfo = userService.geUserById(userId.intValue());
        IntegralVO integral= integralService.queryIntegral(IntegralDTO.builder().accountId(userId.intValue()).build());


        RequestContext.setUserAccountInfoCtx(RequestContext.UserAccountInfoCtx.builder().
                accountID(integral.getId()).
                userID(userId).
                componyCode(userInfo.getCompanyCode()).
                build());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        RequestContext.remove();
    }
}